import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    ComboboxItemDto,
    CommonLookupServiceProxy,
    SettingScopes,
    HostSettingsEditDto,
    HostSettingsServiceProxy,
    SendTestEmailInput,
    JsonClaimMapDto
} from '@shared/service-proxies/service-proxies';
import { FormControl } from '@angular/forms';
import { FileUploader } from 'ng2-file-upload';
import { FileUploadHelper } from '@shared/helpers/FileUploadHelper';
import { AppConsts } from '@shared/AppConsts';
import { TokenService } from 'abp-ng2-module';
import { AppLocalizationService } from '@app/shared/common/localization/app-localization.service';

@Component({
    templateUrl: './host-settings.component.html',
    animations: [appModuleAnimation()]
})
export class HostSettingsComponent extends AppComponentBase implements OnInit {
    @ViewChild('emailSmtpSettingsForm') emailSmtpSettingsForm: FormControl;

    loading = false;
    settings: HostSettingsEditDto;
    editions: ComboboxItemDto[] = undefined;
    testEmailAddress: string = undefined;
    showTimezoneSelection = abp.clock.provider.supportsMultipleTimezone;
    defaultTimezoneScope: SettingScopes = SettingScopes.Application;

    usingDefaultTimeZone = false;
    initialTimeZone: string = undefined;

    enabledSocialLoginSettings: string[];

    wsFederationClaimMappings: { key: string, value: string }[];
    openIdConnectClaimMappings: { key: string, value: string }[];
    initialEmailSettings: string;

    
    waterMarkImageUploader: FileUploader;

    constructor(
        injector: Injector,
        private _tokenService: TokenService,
        private _hostSettingService: HostSettingsServiceProxy,
        private _commonLookupService: CommonLookupServiceProxy,
        private _appLocalizationService: AppLocalizationService
    ) {
        super(injector);
    }

    loadHostSettings(): void {
        const self = this;
        self._hostSettingService.getAllSettings()
            .subscribe(setting => {
                self.settings = setting;
                self.initialTimeZone = setting.general.timezone;
                self.usingDefaultTimeZone = setting.general.timezoneForComparison === self.setting.get('Abp.Timing.TimeZone');

                this.wsFederationClaimMappings = this.settings.externalLoginProviderSettings.openIdConnectClaimsMapping
                    .map(item => {
                        return {
                            key: item.key,
                            value: item.claim
                        };
                    });
                this.openIdConnectClaimMappings = this.settings.externalLoginProviderSettings.openIdConnectClaimsMapping
                    .map(item => {
                        return {
                            key: item.key,
                            value: item.claim
                        };
                    });

                this.initialEmailSettings = JSON.stringify(self.settings.email);
            });
    }

    loadEditions(): void {
        const self = this;
        self._commonLookupService.getEditionsForCombobox().subscribe((result) => {
            self.editions = result.items;

            const notAssignedEdition = new ComboboxItemDto();
            notAssignedEdition.value = null;
            notAssignedEdition.displayText = self.l('NotAssigned');

            self.editions.unshift(notAssignedEdition);
        });
    }

    init(): void {
        const self = this;
        self.testEmailAddress = self.appSession.user.emailAddress;
        self.showTimezoneSelection = abp.clock.provider.supportsMultipleTimezone;
        self.loadHostSettings();
        self.loadEditions();
    }

    ngOnInit(): void {
        const self = this;
        self.init();
        this.initUploaders();
    }

    sendTestEmail(): void {
        const self = this;
        const input = new SendTestEmailInput();
        input.emailAddress = self.testEmailAddress;

        if (this.initialEmailSettings !== JSON.stringify(this.settings.email)) {
            this.message.confirm(
                this.l('SendEmailWithSavedSettingsWarning'),
                this.l('AreYouSure'),
                isConfirmed => {
                    if (isConfirmed) {
                        self._hostSettingService.sendTestEmail(input).subscribe(result => {
                            self.notify.info(self.l('TestEmailSentSuccessfully'));
                        });
                    }
                }
            );
        } else {
            self._hostSettingService.sendTestEmail(input).subscribe(result => {
                self.notify.info(self.l('TestEmailSentSuccessfully'));
            });
        }
    }

    saveAll(): void {
        if (!this.isSmtpSettingsFormValid()) {
            return;
        }

        this.alterValues();

        this._hostSettingService.updateAllSettings(this.settings).subscribe(result => {
            this.notify.info(this.l('SavedSuccessfully'));

            if (abp.clock.provider.supportsMultipleTimezone 
                && this.usingDefaultTimeZone 
                && this.initialTimeZone !== this.settings.general.timezone) {
                    this.message.info(this.l('TimeZoneSettingChangedRefreshPageNotification')).then(() => {
                    window.location.reload();
                });
            }

            this.initialEmailSettings = JSON.stringify(this.settings.email);
        });
    }

    
    private alterValues(){
        if (!this.settings.tenantManagement.defaultEditionId || this.settings.tenantManagement.defaultEditionId.toString() === 'null') {
            this.settings.tenantManagement.defaultEditionId = null;
        }

        if(this.settings.security.userPasswordExpires.maximumNumberOfDays < 1){
            this.settings.security.userPasswordExpires.maximumNumberOfDays = 1;
        }
    }

    isSmtpSettingsFormValid(): boolean {
        return this.emailSmtpSettingsForm.valid;
    }


    initUploaders(): void {
        this.waterMarkImageUploader = FileUploadHelper.createUploader(
            '/B/FileUpload/UploadWaterMarkImage',
            ()=> this._tokenService.getToken(),
            result => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.settings.otherSettings.waterMarkImagePath = result;
            },
            error=>{
                this.notify.error(error.message);
            }
        );
    }

    onWaterMarkImageInputChange(event: any) {
        if (this.waterMarkImageUploader.isUploading) {
            event.target.value = null;
            return;
        }

        if (event.target.files && event.target.files.length > 0) {
            let file = event.target.files[0];
            event.target.value = null;
            if (!FileUploadHelper.check(file.name, 'jpg|jpeg|png', file.size, 2, this.notify, this._appLocalizationService)) {
                this.waterMarkImageUploader.addToQueue([file]);
            }
        }

        if (this.waterMarkImageUploader.queue.length > 0) {
            this.waterMarkImageUploader.uploadAll();
        }
    }

    getUrl(url: string) {
        return FileUploadHelper.getUrl(url);
    }

    lookOver(picurl:string) {
        abp.event.trigger(AppConsts.EventName.showImageView, FileUploadHelper.getUrl(picurl));
    }
}
